//
//  GAOStatusesPictureView.swift
//  Weibo28
//
//  Created by 高辰 on 16/5/16.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

//item之间的间距
private let itemMargin = CGFloat(5)
//计算每一个item的宽度
private let itemWidth = (ScreenWidth - StatusTableViewCellMargin*2 - itemMargin*2) / 3

private let PictureViewReuseIdentifier = "PictureViewReuseIdentifier"

class GAOStatusesPictureView: UICollectionView, UICollectionViewDataSource, UICollectionViewDelegate {
    
    var pic_urls: [GAOPictureModel]? {
        didSet {
            countLabel.text = "\(pic_urls?.count ?? 0)"
            //更新约束
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(makeSize(pic_urls?.count ?? 0))
            }
            //刷新数据
            reloadData()
        }
    }
    
    private lazy var countLabel: UILabel = UILabel(textColor: UIColor.redColor(), fontSize: 15)
    
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        flowLayout.minimumInteritemSpacing = itemMargin
        flowLayout.minimumLineSpacing = itemMargin
        
        super.init(frame: frame, collectionViewLayout: flowLayout)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private func setupUI() {
        addSubview(countLabel)
        
        countLabel.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self)
        }
        //设置代理
        dataSource = self
        delegate = self
        //注册cell
        registerClass(GAOStatusesPictureViewCell.self, forCellWithReuseIdentifier: PictureViewReuseIdentifier)
    }
    
    private func makeSize(count: Int) -> CGSize {
        
        //行数
        let row = (count - 1) / 3 + 1
        //列数
        let col = count > 3 ? 3 : count
        //pictureView的宽度
        let pictureViewWidth = itemWidth * CGFloat(col) + itemMargin * CGFloat(col - 1)
        //pictureView的高度
        let pictureViewHeight = itemWidth * CGFloat(row) + itemMargin * CGFloat(row - 1)
        return CGSize(width: pictureViewWidth, height: pictureViewHeight)
    }
    
}

//  MARK: UICollectionViewDelegate
extension GAOStatusesPictureView {
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let photoBrowser = SDPhotoBrowser()
        photoBrowser.delegate = self
        
        photoBrowser.currentImageIndex = indexPath.item
        photoBrowser.imageCount = pic_urls?.count ?? 0
        //设置来源视图
        photoBrowser.sourceImagesContainerView = self
        photoBrowser.show()
    }
    
}

extension GAOStatusesPictureView: SDPhotoBrowserDelegate {
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        let indePath = NSIndexPath(forItem: index, inSection: 0)
        let cell = self.cellForItemAtIndexPath(indePath) as! GAOStatusesPictureViewCell
        
        return cell.pictureView.image
        
    }
    
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        let urlStr = pic_urls![index].thumbnail_pic!.stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle")
        return NSURL(string: urlStr)
    }
    
}




//  MARK: UICollectionViewDataSource
extension GAOStatusesPictureView {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pic_urls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PictureViewReuseIdentifier, forIndexPath: indexPath) as! GAOStatusesPictureViewCell
        
        cell.pictureModel = pic_urls?[indexPath.item]
        return cell
    }
    
    
}


class GAOStatusesPictureViewCell: UICollectionViewCell {
    
    var pictureModel: GAOPictureModel? {
        didSet {
            if let urlStr = pictureModel?.thumbnail_pic {
                pictureView.sd_setImageWithURL(NSURL(string: urlStr), placeholderImage: UIImage(named: "timeline_image_placeholder"))
                GIFView.hidden = !urlStr.hasSuffix(".gif")
                
            }
        }
    }
    
    lazy var pictureView: UIImageView = {
        let imageView = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
        //让图片按比例显示
        imageView.contentMode = .ScaleToFill
        imageView.clipsToBounds = true
        return imageView
    }()
    
    //GIF图片标识View
    private lazy var GIFView: UIImageView = {
        let imageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
        return imageView
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        contentView.addSubview(pictureView)
        contentView.addSubview(GIFView)
        //添加约束
        pictureView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        GIFView.snp_makeConstraints { (make) -> Void in
            make.trailing.equalTo(pictureView)
            make.bottom.equalTo(pictureView)
        }
    }
    
}

